import setting from '../setting'

let devUrl = setting.BASE_URL

const isDev = process.env.NODE_ENV === 'development'

// #ifdef H5
devUrl = ''
// #endif

const baseUrl = devUrl

const POST = 'POST'
const UPLOAD = 'UPLOAD'
const SUCCESS_CODE = 200 // 请求成功
const LOGOUT_CODE = 401 // 未登录
const UN_AUTH = 600 // 没有手机号，未授权
const REFRESH_CODE = 506

const getHeader = () => {
  const accessToken = uni.getStorageSync('Token') || ''
  return {
    Authorization: 'Bearer ' + accessToken
  }
}
/**
 *
 * @param {string} method 请求方法
 * @param {string} url api地址
 * @param {string} data 入参
 */

const request = (url, data, method = POST, isLogin = true) =>
  new Promise((resolve, reject) => {
    if (method !== UPLOAD) {
      uni.request({
        url: `${baseUrl}/${url}`,
        method,
        data,
        header: isLogin ? getHeader(isLogin) : {},
        success(res) {
          // 请求成功
          const data = res.data
          if (data.code === SUCCESS_CODE) {
            resolve(data.data)
          } else {
            // 其他异常
            if (data.code === REFRESH_CODE) {
              uni.showToast({ title: 'REFRESH_CODE', icon: 'none' })
            } else if (data.code === UN_AUTH) {
              uni.showToast({
                title: '请先绑定手机号',
                icon: 'error',
                duration: 1000,
                // 未登录，跳转登陆页授权
                complete() {
                  setTimeout(() => {
                    uni.navigateTo({
                      url: `/pages/login/phone`
                    })
                  }, 1000)
                }
              })
              return
            } else if (data.code === LOGOUT_CODE) {
              let page = getCurrentPages().pop()
              uni.showToast({
                title: '请先登陆',
                icon: 'error',
                duration: 1000,
                // 未登录，跳转登陆页授权
                complete() {
                  uni.navigateTo({
                    url: `/pages/login/index?url=${page.$page.fullPath}`
                  })
                }
              })
              return
            } else {
              uni.showToast({ title: data.msg, icon: 'none' })
            }
            reject(data)
          }
        },

        fail(err) {
          console.log(err)
          // 请求失败
          reject(new Error('请检查网络'))
        }
      })
    } else {
      console.log(data, url)
      uni.uploadFile({
        file: data,
        filePath: data.path,
        name: 'file',
        url: `${baseUrl}/${url}`,
        header: getHeader(method, url, true),
        success: (resObj) => {
          const res = JSON.parse(resObj.data)
          if (res.code === SUCCESS_CODE) {
            resolve(res.data)
          } else {
            // 其他异常
            reject(res.msg)
          }
        },
        fail: (err) => {
          reject(new Error('上传失败:' + JSON.stringify(err)))
        }
      })
    }
  })

export default request
